// pages/shipment/detail/detail.js
import CoordinateUtil from '../../../utils/CoordinateUtil'
import {
  getShipmentByIdApi,
  receptionShipment,
  queryLineByShipmentId,
  getCarTravel,
} from '../../../utils/api'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shipment: {}, // 配送单
    shipmentLine: [], //发货明细行
    markers: [], // 标记点集合
    carPoint: {}, // 车辆点位
    polyline: [], // 轨迹点集合
    from: {}, //起点坐标
    to: {}, //终点坐标
    fromDistance: 0, //到起点距离
    toDistance: 0, // 到终点距离
    shipDistance: 0, // 配送距离
    stateMap: {},
    isDriver: false, //是否是司机角色， 司机角色拥有操作配送单的按钮
    isbottom: 0,
    resultImage: [],
    shipmentImage: [],
    animationData: [],
    show: false,
    menuAnim: ""
  },
  touchStart(e) {
    var that = this;
    that.setData({
      touchx: e.changedTouches[0].clientX,
      touchy: e.changedTouches[0].clientY
    })
  },
  touchEnd(e) {
    var that = this;
    let x = e.changedTouches[0].clientX;
    let y = e.changedTouches[0].clientY;
    let turn = "";
    if (x - that.data.touchx > 50 && Math.abs(y - that.data.touchy) < 50) { //右滑
      turn = "right";
    } else if (x - that.data.touchx < -50 && Math.abs(y - that.data.touchy) < 50) { //左滑
      turn = "left";
    }
    if (y - that.data.touchy > 50 && Math.abs(x - that.data.touchx) < 50) { //下滑
      turn = "down";
    } else if (y - that.data.touchy < -50 && Math.abs(x - that.data.touchx) < 50) { //上滑
      turn = "up";
    }
    //上滑触发
    if (turn == 'up') {
      this.setData({
        isbottom: 1
      })
      this.mapCtx = wx.createMapContext('map');
      let shipment = this.data.shipment
      if (shipment.rowstate === 'COMPLETED') {
        this.showTravel(1, shipment)
      } else {
        let res = CoordinateUtil.transformFromWGSToGCJ(shipment.senderLatitude, shipment.senderLongitude);
        let sender = CoordinateUtil.transformFromBaiduToGCJ(shipment.senderLatitude, shipment.senderLongitude);
        let from = {
          latitude: sender.latitude,
          longitude: sender.longitude,
          iconPath: "/static/location.png",
          id: 1,
          width: 40,
          height: 40,
          label: {
            content: '起点',
            anchorX: -12
          }
        }
        let receiver = CoordinateUtil.transformFromBaiduToGCJ(shipment.receiverLatitude, shipment.receiverLongitude);
        let to = {
          latitude: receiver.latitude,
          longitude: receiver.longitude,
          iconPath: "/static/location.png",
          id: 2,
          width: 40,
          height: 40,
          label: {
            content: '终点',
            anchorX: -12
          }
        }
        let carPoint = {
          latitude: res.latitude,
          longitude: res.longitude,
          id: 3,
          width: 40,
          height: 40
        }
        let markers = [from, to]
        let fromDistance = CoordinateUtil.getDistanceKm(from, carPoint)
        let toDistance = CoordinateUtil.getDistanceKm(to, carPoint)
        let shipDistance = CoordinateUtil.getDistanceKm(from, to)

        this.setData({
          markers: markers,
          from: from,
          to: to,
          carPoint: carPoint,
          fromDistance: fromDistance,
          toDistance: toDistance,
          shipDistance: shipDistance
        })
        // 缩放视野展示所有点位
        let padding = 150
        this.mapCtx.includePoints({
          points: [...markers, carPoint],
          padding: [padding, padding, padding, padding]
        });
      }
    }
    //根据方向进行操作
    if (turn == 'down') {
      this.setData({
        isbottom: 0
      })
      //下滑触发操作
      this.mapCtx = wx.createMapContext('map');
      let shipment = this.data.shipment
      if (shipment.rowstate === 'COMPLETED') {
        this.showTravel(1, shipment)
      } else {
        let res = CoordinateUtil.transformFromWGSToGCJ(shipment.senderLatitude, shipment.senderLongitude);
        let sender = CoordinateUtil.transformFromBaiduToGCJ(shipment.senderLatitude, shipment.senderLongitude);
        let from = {
          latitude: sender.latitude,
          longitude: sender.longitude,
          iconPath: "/static/location.png",
          id: 1,
          width: 40,
          height: 40,
          label: {
            content: '起点',
            anchorX: -12
          }
        }
        let receiver = CoordinateUtil.transformFromBaiduToGCJ(shipment.receiverLatitude, shipment.receiverLongitude);
        let to = {
          latitude: receiver.latitude,
          longitude: receiver.longitude,
          iconPath: "/static/location.png",
          id: 2,
          width: 40,
          height: 40,
          label: {
            content: '终点',
            anchorX: -12
          }
        }
        let carPoint = {
          latitude: res.latitude,
          longitude: res.longitude,
          id: 3,
          width: 40,
          height: 40
        }
        let markers = [from, to]
        let fromDistance = CoordinateUtil.getDistanceKm(from, carPoint)
        let toDistance = CoordinateUtil.getDistanceKm(to, carPoint)
        let shipDistance = CoordinateUtil.getDistanceKm(from, to)

        this.setData({
          markers: markers,
          from: from,
          to: to,
          carPoint: carPoint,
          fromDistance: fromDistance,
          toDistance: toDistance,
          shipDistance: shipDistance
        })
        // 缩放视野展示所有点位
        let padding = 60
        this.mapCtx.includePoints({
          points: [...markers, carPoint],
          padding: [padding, padding, padding, padding]
        });
      }

    }
  },
  makePhoneCall(e) {
    var phoneNumber = e.target.dataset.phoneNumber
    phoneNumber = phoneNumber.split(',').filter((item) => {
      return item.length > 0
    })
    wx.showActionSheet({
      itemList: phoneNumber,
      success(res) {
        wx.makePhoneCall({
          phoneNumber: phoneNumber[res.tapIndex]
        })
      }
    })
  },
  jumpToUpload(e) {
    let {
      type,
      shipmentId,
      id
    } = e.target.dataset
    wx.navigateTo({
      url: `../upload/upload?type=${type}&shipmentId=${shipmentId}&id=${id}`,
    })
  },
  accept() {
    receptionShipment({
      reason: '',
      recvFlag: 0,
      shipmentId: this.data.shipment.shipmentId
    }, res => {
      wx.showToast({
        title: '操作成功',
      })
      this.onLoad({
        id: this.data.shipment.id
      })
    })
  },
  refuse() {
    wx.showModal({
      editable: true, //显示输入框
      placeholderText: '输入拒绝原因', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          let reason = res.content
          receptionShipment({
            reason: reason,
            recvFlag: 1,
            shipmentId: this.data.shipment.shipmentId
          }, res => {
            wx.showToast({
              title: '操作成功',
            })
            wx.navigateBack()
          })
        } else {
          console.log('用户点击了取消')
        }
      }
    })
  },
  navigateTo(e) {
    let p = e.target.dataset.type === 'to' ? this.data.to : this.data.from
    this.mapCtx.openMapApp({
      latitude: p.latitude,
      longitude: p.longitude,
      destination: this.data.shipment.receiverAddress
    })
    // console.log("1213", p.latitude, p.longitude)
  },
  showTravel(pageIndex, shipment) {
    let beginTime = shipment.actualShipDate
    let endTime = shipment.completeDate
    // let beginTime = '2022-08-25 08:11:52'
    // let endTime = '2022-12-26 08:11:52'
    let that = this
    getCarTravel({
      plateNumber: shipment.plateNumber,
      startTime: beginTime,
      endTime: endTime
    }, res => {
      let pois = res.result
      if (typeof pois === 'undefined' || pois.length == 0) {
        return
      }
      let points = pois.map(v => CoordinateUtil.transformFromWGSToGCJ(v.Lat, v.Lng)).map((v, i) => {
        return {
          latitude: v.latitude,
          longitude: v.longitude,
          id: i + 1,
          width: 40,
          height: 40
        }
      })
      let sender = CoordinateUtil.transformFromBaiduToGCJ(shipment.senderLatitude, shipment.senderLongitude);
      let from = {
        latitude: sender.latitude,
        longitude: sender.longitude,
        iconPath: "/static/location.png",
        id: 1,
        width: 40,
        height: 40,
        label: {
          content: '起点',
          anchorX: -12
        }
      }
      let receiver = CoordinateUtil.transformFromBaiduToGCJ(shipment.receiverLatitude, shipment.receiverLongitude);
      let to = {
        latitude: receiver.latitude,
        longitude: receiver.longitude,
        iconPath: "/static/location.png",
        id: 2,
        width: 40,
        height: 40,
        label: {
          content: '终点',
          anchorX: -12
        }
      }
      let shipDistance = CoordinateUtil.getDistanceKm(from, to)
      let markers = [from, to]
      that.setData({
        polyline: [{
          points: points,
          arrowLine: true,
          color: "#53B771",
          width: 7,
        }],
        markers: markers,
        from: from,
        to: to,
        shipDistance: shipDistance
      })
      // 缩放视野展示所有点位
      let padding = 60
      that.mapCtx.includePoints({
        points: [...markers, ...points],
        padding: [padding, padding, padding, padding]
      });
    })
  },
  showPoint() {
    this.mapCtx = wx.createMapContext('map');
    let shipment = this.data.shipment
    if (shipment.rowstate === 'COMPLETED') {
      this.showTravel(1, shipment)
    } else {
      // wx.getLocation({
      //   success: res => {
      //     res = CoordinateUtil.transformFromWGSToGCJ(res.latitude, res.longitude);
      //     let sender = CoordinateUtil.transformFromBaiduToGCJ(shipment.senderLatitude, shipment.senderLongitude);
      //     let from = {
      //       latitude: sender.latitude, 
      //       longitude: sender.longitude,
      //       iconPath: "/static/location.png",
      //       id: 1,
      //       width: 40,
      //       height: 40,
      //       label: {
      //         content: '起点',
      //         anchorX: -12
      //       }
      //     }
      //     let receiver = CoordinateUtil.transformFromBaiduToGCJ(shipment.receiverLatitude, shipment.receiverLongitude);
      //     let to = {
      //       latitude: receiver.latitude, 
      //       longitude: receiver.longitude,
      //       iconPath: "/static/location.png",
      //       id: 2,
      //       width: 40,
      //       height: 40,
      //       label: {
      //         content: '终点',
      //         anchorX: -12
      //       }
      //     }
      //     let carPoint = {
      //       latitude: res.latitude,
      //       longitude: res.longitude,
      //       id: 3,
      //       width: 40,
      //       height: 40
      //     }
      //     let markers = [from, to]
      //     let fromDistance = CoordinateUtil.getDistanceKm(from, carPoint)
      //     let toDistance = CoordinateUtil.getDistanceKm(to, carPoint)
      //     let shipDistance = CoordinateUtil.getDistanceKm(from, to)

      //     this.setData({
      //       markers: markers,
      //       from: from,
      //       to: to,
      //       carPoint: carPoint,
      //       fromDistance: fromDistance,
      //       toDistance: toDistance,
      //       shipDistance: shipDistance
      //     })
      //     // 缩放视野展示所有点位
      //     let padding = 60
      //     this.mapCtx.includePoints({
      //       points: [...markers, carPoint],
      //       padding: [padding, padding, padding, padding]
      //     });
      //   }
      // })
      let res = CoordinateUtil.transformFromWGSToGCJ(shipment.senderLatitude, shipment.senderLongitude);
      let sender = CoordinateUtil.transformFromBaiduToGCJ(shipment.senderLatitude, shipment.senderLongitude);
      let from = {
        latitude: sender.latitude,
        longitude: sender.longitude,
        iconPath: "/static/location.png",
        id: 1,
        width: 40,
        height: 40,
        label: {
          content: '起点',
          anchorX: -12
        }
      }
      let receiver = CoordinateUtil.transformFromBaiduToGCJ(shipment.receiverLatitude, shipment.receiverLongitude);
      let to = {
        latitude: receiver.latitude,
        longitude: receiver.longitude,
        iconPath: "/static/location.png",
        id: 2,
        width: 40,
        height: 40,
        label: {
          content: '终点',
          anchorX: -12
        }
      }
      let carPoint = {
        latitude: res.latitude,
        longitude: res.longitude,
        id: 3,
        width: 40,
        height: 40
      }
      let markers = [from, to]
      let fromDistance = CoordinateUtil.getDistanceKm(from, carPoint)
      let toDistance = CoordinateUtil.getDistanceKm(to, carPoint)
      let shipDistance = CoordinateUtil.getDistanceKm(from, to)

      this.setData({
        markers: markers,
        from: from,
        to: to,
        carPoint: carPoint,
        fromDistance: fromDistance,
        toDistance: toDistance,
        shipDistance: shipDistance
      })
      // 缩放视野展示所有点位
      let padding = 60
      this.mapCtx.includePoints({
        points: [...markers, carPoint],
        padding: [padding, padding, padding, padding]
      });
    }
  },
  showLineInfo() {
    queryLineByShipmentId({
      shipmentId: this.data.shipment.shipmentId
    }, res => {
      this.setData({
        shipmentLine: res.result
      })
    })
  },
  /**
   * 预览图片
   */
  previewImg(e) {
    let type = e.currentTarget.dataset.type;
    let index = e.currentTarget.dataset.index;
    let img_arr = type === 'resultImage' ? this.data.resultImage : this.data.shipmentImage;
    wx.previewImage({
      current: img_arr[index],
      urls: img_arr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    getShipmentByIdApi({
      id: options.id
    }, res => {
      this.setData({
        shipment: res.result,
        resultImage: res.result.resultImage.split(',').filter(i => i.length > 0).map(i => app.globalData.imgServer + i),
        shipmentImage: res.result.shipmentImage.split(',').filter(i => i.length > 0).map(i => app.globalData.imgServer + i),
        stateMap: app.globalData.stateMap,
        isDriver: app.globalData.logiRole.role_code === 'logi-driver'
      })
      this.showPoint()
      this.showLineInfo()
    })
    // this.onScrollDom('#fix-view', this)
  },
  //滚动监听
  onPageScroll: function (event) {
    // this.onScrollWindow(event, this)
    this.setData({
      isbottom: 1
    })
    // var animation = wx.createAnimation({
    //   duration: 400,
    //   timingFunction: "linear",
    //   dalay: 0,
    //   transformOrign: "50% 50% 0"
    // });
    // 设置动画
    // animation.rotate(90).step();
    // step 代表步
    // animation.rotate(90).scale(2).step(); // 旋转放大
    // animation.scaleY(0.97).step()

    // animation.rotate(90).step();
    // animation.scale(90).step();
    // 将动画数据导出 并进行设置
    // this.setData({
    //   animationData: animation.export()
    // });
    // this.setData({
    //   show: true
    // });
  },
  /**
   * 滚动元素高度
   * @param id 元素选择器
   * @param self 绑定this对象
   */
  // onScrollDom(id, self, options = {}) {

  //   wx.createSelectorQuery().select(id).boundingClientRect(function (rect) {
  //     self.setData({
  //       menuHeight: options.height || rect.bottom
  //     })
  //   }).exec()
  // },
  /**
   * 计算滚动距离
   * @param event 滚动元素
   * @param self 绑定this对象
   */
  // onScrollWindow(event, self) {
  //   let scroll = event.scrollTop; //当前的距离顶部的高度
  //   let scrollTop = self.data.scrollTop; //记录的距离顶部的高度
  //   let height = self.data.menuHeight; //菜单的高度
  //   let show = self.data.showMenu; //菜单的显示状态
  //   //是否超过开始隐藏的高度
  //   if (scroll > height) {
  //     if ((scroll < scrollTop) == show) { //超过高度时的上滑或下滑状态一致时
  //       self.setData({
  //         scrollTop: scroll
  //       })
  //     } else { //超过高度时的上滑显示和下滑隐藏
  //       let anim = wx.createAnimation({
  //         timingFunction: 'ease-in-out',
  //         duration: 200,
  //         delay: 0
  //       })
  //       anim.translateY(scroll < scrollTop ? 0 : -height).step();
  //       self.setData({
  //         scrollTop: scroll,
  //         showMenu: scroll < scrollTop,
  //         menuAnim: anim.export()
  //       })
  //     }
  //   } else {
  //     //小于menuHeight并且隐藏时执行显示的动画
  //     if (!show) {
  //       let anim = wx.createAnimation({
  //         timingFunction: 'ease-in-out',
  //         duration: 200,
  //         delay: 0
  //       })
  //       anim.translateY(0).step();
  //       self.setData({
  //         scrollTop: scroll,
  //         showMenu: true,
  //         menuAnim: anim.export()
  //       })
  //     } else {
  //       self.setData({
  //         scrollTop: scroll
  //       })
  //     }
  //   }
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.checkLogin()
    if (this.data.id) {
      this.onLoad({
        id: this.data.id
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },
  onClose() {
    this.setData({
      show: false
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})